import sys
import argparse
import asyncio
import random
import syndicate
from syndicate import patterns as P, actor, dataspace, turn

from syndicate.schema import sturdy
from preserves.schema import load_schema_file

AprilTagProtocol = load_schema_file('./apriltag.bin').apriltag
AprilTag = AprilTagProtocol.AprilTag
print(AprilTag)
Says = AprilTagProtocol.Says

parser = argparse.ArgumentParser(description='Opens a webcam and tracks any detected Apriltags.',
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--address', metavar='\'<tcp "HOST" PORT>\'',
                    help='transport address of the server',
                    default='<ws "ws://localhost:9001/">')
parser.add_argument('--cap', metavar='\'<ref ...>\'',
                    help='capability for the dataspace on the server',
                    default='<ref {oid: "syndicate" sig: #[acowDB2/oI+6aSEC3YIxGg==]}>')
args = parser.parse_args()

@actor.run_system(name = 'aprilTagListener', debug = False)
def main():
    root_facet = turn.active_facet()

    @syndicate.relay.connect(args.address, sturdy.SturdyRef.decode(syndicate.parse(args.cap)))
    def on_connected(ds):
        turn.on_stop(lambda: turn.stop(root_facet))

        @dataspace.during(ds, P.rec('AprilTag', P.CAPTURE, P.CAPTURE, P.CAPTURE))
        def on_apriltag(id, x, y):
            print(f'AprilTag {id} at x:{x} and y:{y}')
